package com.ebeitech.library.util;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Vibrator;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.ebeitech.library.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by alice on 2017/10/25.
 */
public class CommonUtil {

	private static final String FILE_LOG = "Log";

	public static final String FILE_DIR = Environment
			.getExternalStorageDirectory().getPath() + "/tempfile";

	public static final String _LOCK = "_lock";
	public static final String _UNLOCK = "_unlock";
	public static final String LOCK_ = "lock_";
	public static final String UNLOCK_ = "unlock_";

	public static final String EBEI_TECH = "ebeitech";

	/**
	 * 获取存储的根目录
	 * @return
	 */
	public static String getRootCacheFile(Context context) {
		String cachePath;
		if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			return "";
		} else {
			cachePath = context.getExternalCacheDir().getPath();
		}
		cachePath = cachePath.substring(0,cachePath.lastIndexOf("/cache"));
		return cachePath;
	}

	/**
	 * 获取某个应用的文件夹
	 * @param fileName
	 * @return
	 */
	public static String getCacheFile(Context context, String fileName) {
		String filePath = getRootCacheFile(context) + File.separator + fileName;
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return filePath;
	}

	/**
	 * 获取日志目录
	 * @return
	 */
	public static String getLogFile(Context context) {
		return getRootCacheFile(context) + File.separator + FILE_LOG;
	}

	/**
	 * 是否联网
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		String message="是否联网！！！！\n ";
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo=connectivity.getActiveNetworkInfo();
		if (mNetworkInfo!=null){
			if (mNetworkInfo.isAvailable()){
				int netWorkType =mNetworkInfo.getType();
				if(netWorkType==ConnectivityManager.TYPE_WIFI){
					message+="当前网络是WIFI\n ";
				}
				else if(netWorkType==ConnectivityManager.TYPE_MOBILE){
					message+="当前网络是3G\n ";
				}else {
					message+="其它方式\n ";
				}
			}else {
				message+="当前无网络\n ";
			}
		}

		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (NetworkInfo i : info) {
					message+=i.isConnected()+" i.isconnected\n ";
					if (i.isConnected()) {
						Log.i(message);
						/*try {
							FileUtil.saveData(getLogFile() + "/loginTest.txt", message);
						} catch (IOException e1) {
							e1.printStackTrace();
						}*/

						return true;
					}
				}
			}
		}

		return false;
	}

	/**
	 * 是否连接WIFI
	 * @param inContext
	 * @return
	 */
	public static boolean isWiFiConnected(Context inContext) {
		Context context = inContext.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (NetworkInfo networkInfo : info) {
					if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 获取手机MAC地址
	 * @return
	 */
	public static String getLocalMacAddress(Context context) {
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (wifi != null) {
			WifiInfo info = wifi.getConnectionInfo();
			if (info != null) {
				return info.getMacAddress();
			}
		}
		return null;
	}

	/**
	 * 获取手机信息
	 * @return
	 */
	public static String getPhoneBrand(Context context) {
		return Build.BRAND + "_" + Build.DEVICE//eg: Meizu_MX3
				+ ",androidVersion=" + Build.VERSION.RELEASE
				+ ",net=" + (isWiFiConnected(context) ? "WIFI" : "WAN");
	}

	/**
	 * 播放震动
	 * @param context
	 */
	public static void playVibrator(Context context) {
		Vibrator vibrator = (Vibrator) context.getSystemService(Activity.VIBRATOR_SERVICE);
		long[] pattern = { 800, 40, 400, 30 };
		vibrator.vibrate(pattern, -1);
	}

	/**
	 * 播放通知
	 * @param context
	 */
	public static void playNotification(Context context) {
		if (context.getApplicationInfo().targetSdkVersion > 22) {
			try {
				Uri notificationUri = RingtoneManager.getDefaultUri(
						RingtoneManager.TYPE_NOTIFICATION);
				final MediaPlayer mediaPlayer = new MediaPlayer();
				mediaPlayer.setDataSource(context, notificationUri);
				mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
				mediaPlayer.setLooping(false);
				mediaPlayer.prepare();
				mediaPlayer.start();
				mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						mediaPlayer.release();
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			Notification notification = new Notification();
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);
			notification.defaults = Notification.DEFAULT_SOUND;
			mNotificationManager.notify(0, notification);
		}
	}

	public static String getUUID(){
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	public static boolean fileIsExists(String absPath, String fileName) {
		try {
			File f = new File(absPath, fileName);
			if (!f.exists()) {
				return false;
			}
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return true;
	}

	public static void doOpenFile(String file, Context c, boolean isLocked,
								  ProgressDialog dialog) {
		if (isLocked) {
			doOpenFile(file, c, dialog);
		} else {
			doOpenFile(file, c);
		}
	}

	public static void doOpenFile(String file, Context c) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Uri uri = Uri.parse("file://" + file);
		String type = null;
		if (uri.getScheme().equals("file")) {
			String path = uri.getPath();
			int lastDotIndex = path.lastIndexOf('.');
			if (lastDotIndex != -1) {
				type = MimeTypeMap.getSingleton()
						.getMimeTypeFromExtension(
								uri.getPath().substring(lastDotIndex + 1)
										.toLowerCase());
			}
		}
		String tmp = file.toLowerCase();
		if (tmp.endsWith("m4a") || tmp.endsWith("mp3") || tmp.endsWith("wav")
				|| tmp.endsWith("wma") || tmp.endsWith("ogg")
				|| tmp.endsWith("amr")) {
			type = "audio/*";
			playMediaFile(file, c);
			return;
		} else if (tmp.endsWith("apk")) {
			type = "application/vnd.android.package-archive";
		} else if (tmp.endsWith("wmv") || tmp.endsWith("mp4")
				|| tmp.endsWith("3gp") || tmp.endsWith("mov")
				|| tmp.endsWith("avi") || tmp.endsWith("3gpp")) {
			type = "video/*";
		} else if (type == null) {
			if (tmp.endsWith("jpeg") || tmp.endsWith("jpg")
					|| tmp.endsWith("bmp") || tmp.endsWith("png")
					|| tmp.endsWith("gif")) {
				type = "image/*";
			}
		}
		if (type != null) {
			intent.setDataAndType(uri, type);
			try {
				c.startActivity(intent);
			} catch (ActivityNotFoundException e) {
				Toast.makeText(c, R.string.activity_cannot_start,
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(c, R.string.activity_cannot_start,
					Toast.LENGTH_SHORT).show();
		}
	}

	public static void doOpenFile(final String file, final Context c,
								  final ProgressDialog dialog) {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				// TODO Auto-generated method stub
				int lastDotIndex = file.lastIndexOf('.');
				if (lastDotIndex < 0) {
					return null;
				}
				if (file.endsWith(".jpg") || file.endsWith(".jpeg"))
					return file;
				String str = file.substring(lastDotIndex);
				if (!str.contains("."))
					str = "." + str;
				str = str.replace(_LOCK, "");
				SimpleDateFormat format = new SimpleDateFormat(
						"yyyyMMdd_HHmmss");
				String time = format.format((new Date()));
				String unlockFilePath = FILE_DIR + "/" + time
						+ _UNLOCK + str;

				Log.i("path", unlockFilePath);
				boolean result = unlockFile(file, unlockFilePath,
						EBEI_TECH);
				if (result) {
					return unlockFilePath;
				}
				return null;
			}

			/*
			 * (non-Javadoc)
			 *
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);

				if (dialog != null && dialog.isShowing())
					dialog.dismiss();

				if (isStringNullOrEmpty(result))
					return;

				Intent intent = new Intent(Intent.ACTION_VIEW);
				Uri uri = Uri.parse("file://" + result);
				String type = null;
				if (uri.getScheme().equals("file")) {
					String path = uri.getPath();
					int lastDotIndex = path.lastIndexOf('.');
					if (lastDotIndex != -1) {
						type = MimeTypeMap.getSingleton()
								.getMimeTypeFromExtension(
										uri.getPath()
												.substring(lastDotIndex + 1)
												.toLowerCase());
					}
				}
				int mediaType = parseTypeByPath(result);
				if (mediaType == 3) {
					type = "audio/*";
					playMediaFile(result, c);
					return;
				} else if (mediaType == 2) {
					type = "video/*";
				} else if (type == null) {
					if (mediaType == 1) {
						type = "image/*";
					} else if (mediaType == 0) {
						type = "application/vnd.android.package-archive";
					}
				}
				if (type != null) {
					intent.setDataAndType(uri, type);
					try {
						c.startActivity(intent);
						File file = new File(result);
						file.deleteOnExit();
					} catch (ActivityNotFoundException e) {
						Toast.makeText(c, R.string.activity_cannot_start,
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(c, R.string.activity_cannot_start,
							Toast.LENGTH_SHORT).show();
				}
			}
		}.execute();
	}

	public static boolean unlockFile(String lockFilePath,
									 String unlockFilePath, String password) {
		File lockFile = new File(lockFilePath);
		File unlockFile = new File(unlockFilePath);

		if (!lockFile.exists()) {
			return false;
		}

		int pwdBytesLength = password.getBytes().length;
		byte[] pwdBytes = new byte[pwdBytesLength];

		try {
			FileOutputStream fos = new FileOutputStream(unlockFile);
			RandomAccessFile ras = new RandomAccessFile(lockFile, "r");
			long bytesRead = ras.read(pwdBytes);
			if (bytesRead != pwdBytesLength) {
				fos.close();
				ras.close();
				return false;
			}

			String pwdRead = new String(pwdBytes);
			if (!password.equals(pwdRead)) {
				fos.close();
				ras.close();
				return false;
			}

			ras.seek(lockFile.length() - pwdBytesLength);
			bytesRead = ras.read(pwdBytes);
			pwdRead = new String(pwdBytes);

			if (!password.equals(pwdRead)) {
				fos.close();
				ras.close();
				return false;
			}

			byte[] buffer = new byte[1024];
			ras.seek(pwdBytesLength);
			long lockFileLength = lockFile.length() - pwdBytesLength * 2;
			while ((bytesRead = ras.read(buffer)) > 0) {
				long length = unlockFile.length();
				if (length + bytesRead > lockFileLength) {
					bytesRead = lockFileLength - length;
					if(bytesRead > 0){
						fos.write(buffer, 0, (int) bytesRead);
					}
					break;
				} else {
					fos.write(buffer, 0, (int) bytesRead);
				}
			}

			fos.close();
			ras.close();

			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public static boolean isStringNullOrEmpty(String str) {
		return str == null || "".equals(str.trim())
				|| TextUtils.isEmpty(str.trim());
	}

	public static int parseTypeByPath(String path) {
		int type = 0;
		String tmp = path.toLowerCase();
		tmp = tmp.replace(_LOCK, "");
		if (tmp.endsWith("m4a") || tmp.endsWith("mp3") || tmp.endsWith("wav")
				|| tmp.endsWith("wma") || tmp.endsWith("ogg")
				|| tmp.endsWith("amr")) {
			type = 3;// MIME is "audio/*"
		} else if (tmp.endsWith("wmv") || tmp.endsWith("mp4")
				|| tmp.endsWith("3gp") || tmp.endsWith("mov")
				|| tmp.endsWith("avi") || tmp.endsWith("3gpp")) {
			type = 2;// MIME is "video/*"
		} else if (tmp.endsWith("jpeg") || tmp.endsWith("jpg")
				|| tmp.endsWith("bmp") || tmp.endsWith("png")
				|| tmp.endsWith("gif")) {
			type = 1;// MIME is "image/*"
		} else if (tmp.endsWith("apk")) {
			type = 0;// MIME is "application/vnd.android.package-archive"
		}
		return type;
	}

	public static void playMediaFile(String path, Context c) {
		MediaPlayer mediaPlayer = new MediaPlayer();
		try {
			mediaPlayer.setDataSource(path);
			mediaPlayer.prepare();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mediaPlayer.start();
		mediaPlayer
				.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();
						mp = null;
					}
				});
	}
}
